import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { message } from 'ant-design-vue';
import router from './router/router';
import store from './store/index';
import { getToken } from './utils/auth';

NProgress.configure({ showSpinner: false });

const tokenKey = process.env.VUE_APP_TOKEN_KEY;

router.beforeEach(async (_to, _from, _next) => {
  NProgress.start();
  const to = _to;
  const next = _next;
  const hasToken = getToken(tokenKey);
  if (!hasToken) {
    if (to.path !== '/login') {
      next('/login');
      return;
    }
    next();
    return;
  }
  if (to.path === '/login') {
    next();
    return;
  }
  const { roles } = store.state.user;
  // 刷新后
  try {
    if (!roles) {
      await store.dispatch('user/getInfo');
    }
  } catch ({ error }) {
    // 验证失败
    message.error(error);
    next('/login');
  }
  if (store.state.user.roles && !store.state.permission.addRoutes) {
    const arr = await store.dispatch(
      'permission/addRoutes',
      store.state.user.roles,
    );
    console.log('???', arr);
    router.addRoutes(arr);
    router.options.routes = router.options.routes.concat(arr);
    if (to.matched.length === 0) {
      next(to.fullPath);
      return;
    }
    next({
      path: to.path,
      replace: true,
    });
    return;
  }

  next();
});
router.afterEach((_to, _from) => {
  NProgress.done();
  const to = _to;
  const from = _from;
  if (from.meta) {
    if (from.meta.ele) {
      from.meta.ele.style.color = 'rgb(191, 203, 217)';
    }
  }
  if (to.meta) {
    if (to.meta.ele) {
      to.meta.ele.style.color = 'rgb(64, 158, 255)';
    }
  }
});
